package com.gxa.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.gxa.common.Result;
import com.gxa.common.annotation.RequirePermission;
import com.gxa.domain.dto.EmployeeDTO;
import com.gxa.domain.entity.Employee;
import com.gxa.domain.vo.EmployeeQueryVO;
import com.gxa.domain.vo.EmployeeVO;
import com.gxa.service.EmployeeService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

/**
 * 员工管理控制器
 */
@Tag(name = "员工管理", description = "员工信息维护相关接口")
@RestController
@RequestMapping("/employee")
@RequiredArgsConstructor
@Slf4j
public class EmployeeController {

    private final EmployeeService employeeService;

    @Operation(summary = "分页查询员工列表")
    @RequirePermission("员工管理")
    @PostMapping("/page")
    public Result<IPage<EmployeeVO>> pageQuery(@RequestBody EmployeeQueryVO queryVO) {
        try {
            log.info("分页查询员工列表，参数：{}", queryVO);
            IPage<EmployeeVO> page = employeeService.pageQueryVO(queryVO);
            log.info("分页查询员工完成，总记录数：{}", page.getTotal());
            log.info("分页查询员工完成，当前页记录数：{}", page.getRecords().size());
            log.info("分页查询员工完成，返回数据：{}", page.getRecords());
            return Result.success(page);
        } catch (Exception e) {
            log.error("分页查询员工列表失败", e);
            return Result.error("查询员工列表失败：" + e.getMessage());
        }
    }

    @Operation(summary = "根据员工号查询员工")
    @RequirePermission("员工管理")
    @GetMapping("/{employeeId:\\d+}")
    public Result<EmployeeVO> getEmployeeById(@PathVariable Integer employeeId) {
        try {
            log.info("根据员工号查询员工，员工号：{}", employeeId);
            EmployeeVO employee = employeeService.getEmployeeVOById(employeeId);
            if (employee == null) {
                return Result.error("员工不存在");
            }
            return Result.success(employee);
        } catch (Exception e) {
            log.error("根据员工号查询员工失败，员工号：{}", employeeId, e);
            return Result.error("查询员工失败：" + e.getMessage());
        }
    }

    @Operation(summary = "添加员工")
    @RequirePermission("员工管理")
    @PostMapping("/add")
    public Result<Boolean> addEmployee(@RequestBody EmployeeDTO employeeDTO) {
        try {
            log.info("添加员工，员工信息：{}", employeeDTO);
            boolean result = employeeService.addEmployee(employeeDTO);
            if (result) {
                log.info("添加员工成功");
                return Result.success(true);
            } else {
                log.error("添加员工失败");
                return Result.error("添加员工失败");
            }
        } catch (Exception e) {
            log.error("添加员工失败", e);
            return Result.error("添加员工失败：" + e.getMessage());
        }
    }

    @Operation(summary = "更新员工信息")
    @RequirePermission("员工管理")
    @PutMapping("/update")
    public Result<Boolean> updateEmployee(@RequestBody EmployeeDTO employeeDTO) {
        try {
            log.info("更新员工信息，员工信息：{}", employeeDTO);
            boolean result = employeeService.updateEmployee(employeeDTO);
            if (result) {
                log.info("更新员工信息成功");
                return Result.success(true);
            } else {
                log.error("更新员工信息失败");
                return Result.error("更新员工失败");
            }
        } catch (Exception e) {
            log.error("更新员工信息失败", e);
            return Result.error("更新员工失败：" + e.getMessage());
        }
    }

    @Operation(summary = "删除员工")
    @RequirePermission("员工管理")
    @DeleteMapping("/{employeeId:\\d+}")
    public Result<Boolean> deleteEmployee(@PathVariable Integer employeeId) {
        try {
            log.info("删除员工，员工号：{}", employeeId);
            boolean result = employeeService.deleteEmployee(employeeId);
            if (result) {
                log.info("删除员工成功");
                return Result.success(true);
            } else {
                log.error("删除员工失败");
                return Result.error("删除员工失败");
            }
        } catch (Exception e) {
            log.error("删除员工失败，员工号：{}", employeeId, e);
            return Result.error("删除员工失败：" + e.getMessage());
        }
    }

    @Operation(summary = "根据身份证号查询员工")
    @GetMapping("/idCard/{idCardNo}")
    public Result<Employee> getEmployeeByIdCardNo(@PathVariable String idCardNo) {
        try {
            log.info("根据身份证号查询员工，身份证号：{}", idCardNo);
            Employee employee = employeeService.getEmployeeByIdCardNo(idCardNo);
            return Result.success(employee);
        } catch (Exception e) {
            log.error("根据身份证号查询员工失败，身份证号：{}", idCardNo, e);
            return Result.error("查询员工失败：" + e.getMessage());
        }
    }

    @Operation(summary = "根据RFID卡号查询员工")
    @GetMapping("/rfid/{rfidCardNo}")
    public Result<Employee> getEmployeeByRfidCardNo(@PathVariable String rfidCardNo) {
        try {
            log.info("根据RFID卡号查询员工，RFID卡号：{}", rfidCardNo);
            Employee employee = employeeService.getEmployeeByRfidCardNo(rfidCardNo);
            return Result.success(employee);
        } catch (Exception e) {
            log.error("根据RFID卡号查询员工失败，RFID卡号：{}", rfidCardNo, e);
            return Result.error("查询员工失败：" + e.getMessage());
        }
    }


    
    @Operation(summary = "查询所有员工")
    @RequirePermission("员工管理")
    @GetMapping("/list")
    public Result<java.util.List<EmployeeVO>> listAll() {
        try {
            log.info("查询所有员工");
            java.util.List<Employee> employees = employeeService.list();
            java.util.List<EmployeeVO> employeeVOs = employees.stream()
                .map(employee -> {
                    EmployeeVO vo = new EmployeeVO();
                    vo.setEmployeeId(employee.getEmployeeId());
                    vo.setName(employee.getName());
                    vo.setGender(employee.getGender());
                    vo.setIdCardNo(employee.getIdCardNo());
                    vo.setRfidCardNo(employee.getRfidCardNo());
                    vo.setPhone(employee.getPhone());
                    vo.setStatus(employee.getStatus());
                    vo.setOperatorLevel(employee.getOperatorLevel());
                    vo.setBirthDate(employee.getBirthDate());
                    vo.setHireDate(employee.getHireDate());
                    
                    // 转换照片为base64字符串
                    if (employee.getPhoto() != null && employee.getPhoto().length > 0) {
                        vo.setPhoto(java.util.Base64.getEncoder().encodeToString(employee.getPhoto()));
                    }
                    
                    return vo;
                })
                .collect(java.util.stream.Collectors.toList());
            
            log.info("查询所有员工完成，记录数：{}", employeeVOs.size());
            return Result.success(employeeVOs);
        } catch (Exception e) {
            log.error("查询所有员工失败", e);
            return Result.error("查询所有员工失败：" + e.getMessage());
        }
    }
    
    @Operation(summary = "检查工号是否存在")
    @GetMapping("/check/{employeeId}")
    public Result<Boolean> checkEmployeeIdExists(@PathVariable Integer employeeId) {
        try {
            log.info("检查工号是否存在，工号：{}", employeeId);
            Employee employee = employeeService.getEmployeeById(employeeId);
            boolean exists = employee != null;
            log.info("工号 {} 存在状态：{}", employeeId, exists);
            return Result.success(exists);
        } catch (Exception e) {
            log.error("检查工号是否存在失败，工号：{}", employeeId, e);
            return Result.error("检查工号是否存在失败：" + e.getMessage());
        }
    }
}